<?php

namespace app\admin\controller\knowbase;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 知识库文档
 *
 * @icon fa fa-circle-o
 */
class ProjectPage extends Backend
{

    /**
     * ProjectPage模型对象
     * @var \app\common\model\knowbase\ProjectPage
     */
    protected $model = null;
    protected $modelValidate  = true;
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\knowbase\ProjectPage;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("accessTypeList", $this->model->getAccessTypeList());
    }

    
    public function cloneone($ids){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('error_not_record'));
        } else if ($row['type']!='file') {
            $this->error(__('error_clone_type'));
        }
        $data = $row->getData();
        unset($data['id']);
        unset($data['update_time']);
        unset($data['create_time']);
        $data['title'] = $data['title'].'_'.__('btn_clone');
        try{
            \app\common\model\knowbase\ProjectPage::create($data);
        } catch (\Exception $e){
             $this->error($e->getMessage());
        }
        $this->success();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
       
        $this->request->filter(['strip_tags', 'trim']);

        $project_id = $this->request->param('knowbase_project_id',0,'intval');
        $project = \app\common\model\knowbase\Project::get($project_id);
        if (!$project->checkAccess()) {
            $this->error(__('tips_not_access'));
        }
        if ($this->request->isAjax()) {
            $id = $this->request->param('id',0,'intval');
            $from = $this->request->param('from','');
            $list = collection($this->model->with(['project'=>function($q){ return $q->withField('id,title,identify');}])->field('content,attachfiles,password', true)->where('knowbase_project_id',$project_id)->order('weigh DESC,id ASC')->select())->toArray();
            if ($from=='select') {
               
                $max_dir_deep = 0;
                $row = null;
                foreach ($list as $v){
                    if ($v['id']==$id) {
                        $row = $v;
                        $max_dir_deep = $v['deep'];
                        break;
                    }
                }
               
                $nodes = $id?\app\common\model\knowbase\ProjectPage::getAllNodes($id,false):[];
                foreach ($nodes as $v){
                   
                    if ($v['deep']>$max_dir_deep && $v['type']=='dir') {
                        $max_dir_deep = $v['deep'];
                    }
                }
                $list = array_values(array_filter($list,function ($v){
                    return $v['type']=='dir';
                }));
                $nodeIds = array_column($nodes, 'id');
               
                $list = array_values(array_filter($list,function ($v) use($nodeIds,$id){
                    return $v['id']!=$id && (!$id || !in_array($v['id'], $nodeIds));
                   
                }));
               
                $list = array_values(array_filter($list,function ($v) use($max_dir_deep,$row){
                    return !$row || $max_dir_deep - $row['deep'] + $v['deep']<3;
                }));
                Tree::instance()->init($list)->icon = ['&nbsp;', '&nbsp;', '&nbsp;'];
            } else {
                Tree::instance()->init($list)->icon = ['&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'];
            }
            
            $list = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'title');
            
           
            $urls = array_filter($list,function ($v){
                return $v['type']=='url';
            });
            $contents = [];
            if ($urls) {
                $contents = knowbase_groupbyid(collection($this->model->whereIn('id',array_column($urls,'id'))->field('id,content')->select()));
            }
            if ($from=='select') {
                
                 array_unshift($list, ['id'=>0,'title'=>__('root'),'pid'=>-1,'type'=>'dir']);
                
                 if($key = $this->request->request('keyValue')){
                     $list = array_values(array_filter($list,function ($v) use($key){
                         return $v['id']==$key;
                     }));
                 }

                foreach ($list as &$v) {
                    $v['title'] = str_replace("&nbsp;", '　', $v['title']);
                    unset($v);
                }
                
            }
            foreach ($list as &$v) {
                if ($v['type']=='url') {
                    $v['content'] = $contents[$v['id']]['content'];
                }
                unset($v);
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        
        $this->assign('knowbase_project_id',$project_id);
        $this->assign('project', $project);
        $this->assignconfig('project', $project);
        $this->assignconfig('clone', $this->auth->check('knowbase/project_page/cloneone'));  
        $this->assignconfig('url_knowbase_page',config('url_knowbase_page'));   
        $this->assignconfig('url_knowbase_rewrite_page',config('url_knowbase_rewrite_page'));   
        \app\common\model\knowbase\Progress::addLog('project_look',$project_id,$project['title']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        
         if ($project = \app\common\model\knowbase\Project::where('id',$row['knowbase_project_id'])->where('archive_switch',1)->find()) {
             $this->error(__('project_archive', ''));
        }
         
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $this->assignconfig('project',$project);
            $this->assignconfig('page',$row);
            $this->assignconfig('url_knowbase_page',config('url_knowbase_page'));
            $this->assignconfig('url_knowbase_rewrite_page',config('url_knowbase_rewrite_page'));
            \app\common\model\knowbase\Progress::addLog('page_look',$row['id'],$row['title']);
            $this->view->assign('page_history_url',url('knowbase/project_page_history/page_history',['knowbase_project_page_id'=>$row['id'],'from'=>'project_page']));
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
       
        $params = $this->preExcludeFields($params);
        $result = false;
        if ($params['type']=='url') {
            $params['content'] = $params['url'];
            unset($params['url']);
        }
        Db::startTrans();
        try {
            if (empty($params['identify'])) {
                $params['identify'] = NULL;
            }
           
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    
    public function getList() {
        return $this->selectpage();
    }
    
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $project_id = $this->request->get('knowbase_project_id',0,'intval');
            $pid = $this->request->get('pid',0,'intval');
            if ($project_id<=0) {
                $this->error(__('error_request_empty_project_id'));
            } else if ($pid<0) {
                $this->error(__('error_request_empty_pid'));
            }

            $parent_page = null ;
            if ($pid>0 && !($parent_page = \app\common\model\knowbase\ProjectPage::getParentPage($pid, $project_id))) {
                $this->error(__('error_request_related'));
            }
            $project = \app\common\model\knowbase\Project::get($project_id);
            if (!$project) {
                $this->error(__('error_request_related'));
            } else  if ($project['archive_switch']) {
                 $this->error(__('project_archive', ''));
            }
            
            $this->view->assign('project_id',$project_id);
            $this->view->assign('project',$project);
            $this->view->assign('pid',$pid);
            $this->view->assign('parent_page',$parent_page);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if ($params['type']=='url') {
            $params['content'] = $params['url'];
            unset($params['url']);
        }
        $result = false;
        Db::startTrans();
        try {
            if (empty($params['identify'])) {
                $params['identify'] = NULL;
            }
           
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 回收站
     *
     * @return string|Json
     * @throws \think\Exception
     */
    public function recyclebin()
    {
       
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->onlyTrashed()
            ->where($where)
            ->where('knowbase_project_id',$this->request->param('knowbase_project_id',0,'intval'))
            ->order($sort, $order)
            ->paginate($limit);
        $pids = [];
        foreach ($list as $v) {
            $v->nodes = explode(",", $v['nodes']);
            $pids = array_merge($pids,$v->nodes);
        }
        $pids = array_values(array_unique(array_filter($pids)));
        $nodes = knowbase_groupbyid(collection($this->model->useGlobalScope(false)->whereIn('id',$pids)->field('id,title')->select())->toArray());
        foreach ($list as $v){
            $paths = [__('root')];
            foreach ($v['nodes'] as $vv) {
                $paths[] = $nodes[$vv]['title']??'';
            }
            $v->paths = implode("　/　", $paths);
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 真实删除
     *
     * @param $ids
     * @return void
     */
    public function destroy($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
           
           
           
           
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
               
                $result = array_merge([$item['id']],\app\common\model\knowbase\ProjectPage::getAllNodes($item['id']));
                \app\common\model\knowbase\ProjectPage::useGlobalScope(false)->whereIn('id',$result)->delete(true);
                \app\common\model\knowbase\ProjectPageHistory::whereIn('knowbase_project_page_id',$result)->delete();
                $count += count($result);
                 \app\common\model\knowbase\Progress::addLog('page_hard_delete',$item['id'],$item['title']);
               
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


}
